package org.softmed.rest.server.core.handler;

import java.util.ArrayList;
import java.util.List;

import org.softmed.rest.config.Handler;

import com.google.inject.Inject;

public class DefaultHandlerProcessor implements HandlerProcessor {

	@Inject
	List<SpecificHandlerSolver> solvers;
	private SpecificHandlerSolver currentSolver;

	public List<SpecificHandlerSolver> getSolvers() {
		return solvers;
	}

	@Inject
	public void setSolvers(List<SpecificHandlerSolver> solvers) {
		this.solvers = solvers;
	}

	public void solve(Handler handler, HandlerProcessParameters parameters)
			throws Throwable {
		currentSolver = null;

		if (handler == null || !handler.isActive() || handler.getPath() == null)
			return;

		for (SpecificHandlerSolver solver : solvers) {
			if (solver.canSolve(handler)) {
				currentSolver = solver;
				break;
			}
		}

		if (currentSolver != null)
			currentSolver.solve(handler, parameters);
		else
			throw new RuntimeException("No handler was found for "
					+ handler.getPath());

	}

	public boolean isContinueProcessing() {
		if (currentSolver == null)
			return true;
		return currentSolver.isContinueProcessing();
	}

	public HandlerProcessor getClone() {
		DefaultHandlerProcessor clone = new DefaultHandlerProcessor();
		clone.setSolvers(new ArrayList<SpecificHandlerSolver>());
		for (SpecificHandlerSolver specificHandler : solvers) {
			clone.getSolvers().add(specificHandler.getClone());
		}

		return clone;

	}

}
